package com.oig.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {

    private FileUtil(){}

    /**
     * http 下载文件
     * @param url 文件url地址
     * @param destFile 目标文件
     * @return 目标文件
     * @throws IOException
     */
    public static File downloadByUrl(String url, File destFile) throws IOException {
        InputStream stream = null;
        try {
            URL uri = new URL(url);
            HttpURLConnection connection = (HttpURLConnection)uri.openConnection();
            stream = connection.getInputStream(); // get input stream of the file information from the URL
            try (FileOutputStream outputStream = new FileOutputStream(destFile)) {
                int read;
                byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
            }
        } finally {
            if (stream!=null){
                try {
                    stream.close();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return destFile;
    }

}
